<template>
  <div class="detail">
    <van-card
      :num="productNum"
      :price="productData.price/100"
      :desc="productData.content"
      :title="productData.name"
      :thumb="productData.coverImg"
    >
      <template #footer>
        <van-button size="mini" @click="increase">+</van-button>
        <van-button size="mini" @click="reduce">-</van-button>
      </template>
    </van-card>
    <van-button type="primary" size="large" @click="addCart">添加购物车</van-button>
  </div>
</template>

<script>
//获取商品详情接口
import {reqProductDetailAPI} from '@/api/product';
import {addToCart} from '@/api/cart.js';
import {Toast} from 'vant';

export default {
  data() {
    return {
      id:'',        //商品id
      productData:{},  //商品数据
      productNum:1,
    };
  },
  //vue实例创建时调用钩子
  created() {
    this.id = this.$route.params.id;
    this.productData = this.show(this.id);
  },
  methods: {
   async show(id){
    this.productData = await reqProductDetailAPI(id);
   },
    //增加商品数量
    increase(){
    this.productNum++;
    },
    //减少商品数量
    reduce(){
      if (this.productNum>0){
        this.productNum--;
      }
    },
    //添加购物车
   async addCart(){
       const res= await addToCart(this.id,this.productNum);
   if (res.code === 'success'){
     Toast("添加购物车成功");
     this.$router.push('/cart');
   }
   }
  },
};
</script>
<style scoped></style>
